﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using Excel = Microsoft.Office.Interop.Excel;
using MM.Business;
using MM.Entities;

namespace MM
{
    public partial class frmTaoPhieuDH : Form
    {
        string _matau = "";
        string _nguoitao = "";
        string _sConn = "";
        string _plant = "";
        List<CHI_TIET_PDH> lstCTPDH = new List<CHI_TIET_PDH>();
        string[] arrThamSo = new string[10];

        public frmTaoPhieuDH(string sConn)
        {
            InitializeComponent();
            _sConn = sConn;

            _nguoitao = frmDangNhap.objTaiKhoan._soCMND;
            _matau = frmDangNhap.objTau._tenTau2KiTu;
            _plant = frmDangNhap.objTau._plantReferenceSAP;

            this.txtNgayThucHien.Text = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();
            this.txtNguoiThucHien.Text = _nguoitao;

            this.InitThamSo();
        }

        public void InitThamSo()
        {
            THAM_SO objTS = new THAM_SO();
            clsTHAM_SO tsCtrl = new clsTHAM_SO(_sConn);
            objTS = tsCtrl.SelectTHAM_SO("vThuocTinh");
            if (objTS != null && objTS.GiaTri != "")
            {
                arrThamSo = objTS.GiaTri.Split(',');
            }
        }

        private void cmdBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog f = new OpenFileDialog();
            f.Filter = "Text file (*.txt*)|*.txt*";
            f.Title = "CHỌN FILE TEXT TEMPLATE ĐƠN ĐẶT HÀNG - PO ";
            if (f.ShowDialog() == DialogResult.OK)
            {
                lstCTPDH.Clear();
                this.lblSoLuong.Text = "Tổng số dòng: ";
                this.gridControl1.DataSource = lstCTPDH;
                this.txtFileName.Text = f.FileName;
                this.DocNoiDungFileCSV(f.FileName);
                this.lblSoLuong.Text += lstCTPDH.Count.ToString();
            }
        }

        private void DocNoiDungFileCSV(string filename)
        {
            try
            {

                clsTHUOC_TINH ttCtrl = new clsTHUOC_TINH(_sConn);
                List<THUOC_TINH> lstTT = new List<THUOC_TINH>();
                CHI_TIET_PDH oCTPDH;


                StreamReader reader = new StreamReader(File.Open(filename, FileMode.Open));
                int i = 0;
                clsVAT_TU_PHU_TUNG vtptCtrl = new clsVAT_TU_PHU_TUNG(_sConn);
                VAT_TU_PHU_TUNG oVTPT = new VAT_TU_PHU_TUNG();
                clsTRANG_THAI_VTPT ttvtCtrl = new clsTRANG_THAI_VTPT(_sConn);
                TRANG_THAI_VTPT oTTVT = new TRANG_THAI_VTPT();

                int flag = 1;// mac dinh la Xoa
                while (!reader.EndOfStream)
                {
                    try
                    {
                        oCTPDH = new CHI_TIET_PDH();

                        string line = reader.ReadLine();
                        string[] arrvalue = new string[11];
                        arrvalue = line.Split(';');


                        if (i == 0) // header
                        {
                            this.txtSoPhieuPO.Text = arrvalue[0].ToString();
                            this.txtLoaiPO.Text = arrvalue[1].ToString();
                            this.txtPlant.Text = arrvalue[2].ToString();
                            this.txtPlantGui.Text = arrvalue[3].ToString();
                            if (arrvalue[4].ToString() == "D")
                                this.chkXoa.Checked = true;
                            else
                                this.chkXoa.Checked = false;
                            if (this.txtSoPhieuPO.Text.Trim().Length != 10)
                            {
                                chkKhonghople.Checked = true;
                                this.cmdLuu.Enabled = false;
                                MessageBox.Show("ĐỊNH DẠNG TEMPLATE BỊ SAI. KHÔNG TỒN TẠI PO SỐ: " + this.txtSoPhieuPO.Text);
                                return;
                            }
                            else
                            {
                                chkKhonghople.Checked = true;
                                this.cmdLuu.Enabled = false;
                            }
                        }
                        else
                        {
                            oCTPDH.POThamChieuSAP = this.txtSoPhieuPO.Text;
                            oCTPDH.POItem_No = int.Parse(arrvalue[0].ToString());
                            oCTPDH.MaThietBi = arrvalue[1].ToString();

                            oVTPT = new VAT_TU_PHU_TUNG();
                            oVTPT = vtptCtrl.SelectVAT_TU_PHU_TUNG(oCTPDH.MaThietBi.Trim(),frmDangNhap.objTau.maTau);
                            if (oVTPT != null && oVTPT._maVTPT!="")
                            {                              

                                lstTT.Clear();
                                lstTT = ttCtrl.SelectTHUOC_TINHByID(oVTPT._maVTPT);
                                foreach (THUOC_TINH t in lstTT)
                                {
                                    if (Array.IndexOf(arrThamSo, t._maLoaiThuocTinh) >= 0)
                                    {
                                        if (t._giaTriTT != "" && t._giaTriTT != null)
                                        {
                                            oVTPT._tenVTPT += ";" + t._giaTriTT;
                                        }
                                    }
                                }

                                oCTPDH.TenVTPT = oVTPT._tenVTPT;
                                chkKhonghople.Checked = false;
                                this.cmdLuu.Enabled = true;
                            }
                            else
                            {
                                oCTPDH.TenVTPT = "#KHÔNG TỒN TẠI DỮ LIỆU CHO VPTP NÀY";
                                chkKhonghople.Checked = true;
                                this.cmdLuu.Enabled = false;
                                MessageBox.Show("KHÔNG TỒN TẠI VTPT: " + oCTPDH.MaThietBi);
                                return;
                            }


                            oCTPDH.SoLuong = float.Parse(arrvalue[2].ToString());
                            oCTPDH.MaPhieuYeuCau = arrvalue[3].ToString();

                            oCTPDH.ItemCategory = arrvalue[4].ToString();

                            if (oCTPDH.ItemCategory != "U")
                            {
                                oTTVT = new TRANG_THAI_VTPT();
                                oTTVT = ttvtCtrl.usp_SelectTRANG_THAI_VTPTByItemCategory(oCTPDH.ItemCategory);
                                if (oTTVT != null)
                                {
                                    oCTPDH.TenTrangThai = oTTVT.TenTrangThai;
                                    oCTPDH.MaTrangThai = oTTVT.MaTrangThai;
                                    chkKhonghople.Checked = false;
                                    this.cmdLuu.Enabled = true;
                                }
                                else
                                {

                                    oCTPDH.MaTrangThai = -1;
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    return;
                                }
                            }



                            string d = (arrvalue[5].ToString().Trim().Substring(0, 2));
                            string m = (arrvalue[5].ToString().Trim().Substring(3, 2));
                            string y = (arrvalue[5].ToString().Trim().Substring(6, 4));

                            try
                            {
                                oCTPDH.NgayGiaoHang = Convert.ToDateTime(m + "/" + d + "/" + y);
                            }
                            catch { oCTPDH.NgayGiaoHang = Convert.ToDateTime(d + "/" + m + "/" + y); }


                            oCTPDH.TinhTrang = arrvalue[6].ToString() == "D" ? 1 : 0;

                            if (flag == 1 && (oCTPDH.TinhTrang == 0 || (oCTPDH.TinhTrang==1 && i==1) ))
                            {
                                flag = 0;
                            }

                            // ko dùng thông tin Valuation Type arrvalue[7] của template PO ( vì từ Itemcategory có thể bít đc Valuation Type

                            oCTPDH.AccAssignment = arrvalue[8].ToString().Trim();
                            oCTPDH.MaTaiSan = arrvalue[9].ToString().Trim();

                            if (oCTPDH.ItemCategory == "L") // gia cong
                            {
                                string sComponent = "";
                                sComponent = arrvalue[10].ToString().Trim();
                                if (sComponent == "")
                                {
                                    chkKhonghople.Checked = true;
                                    this.cmdLuu.Enabled = false;
                                    MessageBox.Show("KHÔNG TỒN TẠI DỮ LIỆU CÁC VTPT CẦN ĐI GIA CÔNG ĐỂ TẠO THÀNH PHẨM VỚI MÃ VTPT: " + oCTPDH.MaThietBi);
                                    return;
                                }
                                List<string> iComponent = new List<string>(sComponent.Split('#'));
                                for (int c = 0; c < iComponent.Count; c++)
                                {
                                    List<string> items = new List<string>(iComponent[c].Split('$'));
                                    if (items.Count != 3)
                                    {
                                        chkKhonghople.Checked = true;
                                        this.cmdLuu.Enabled = false;
                                        MessageBox.Show("DỮ LIỆU VTPT CẦN ĐI GIA CÔNG ĐỂ TẠO THÀNH PHẨM CÓ MÃ VTPT: " + oCTPDH.MaThietBi+" KHÔNG HỢP LỆ");
                                        return;
                                    }
                                    CHI_TIET_PDH_COMPONENT oComponent = new CHI_TIET_PDH_COMPONENT();
                                    oComponent.MaThietBi = items[0];
                                    oComponent.SoLuong = float.Parse(items[1]);
                                    oComponent.Plant = items[2];

                                    oCTPDH.lstComponent.Add(oComponent);
                                }
                            }

                            oCTPDH.NgayTao = DateTime.Today;
                            oCTPDH.NguoiTao = _nguoitao;



                            lstCTPDH.Add(oCTPDH);

                        }

                        i++;
                    }
                    catch (Exception ex)
                    {                        
                        //MessageBox.Show(ex.Message);
                    }
                }
                this.gridControl1.RefreshDataSource();
               
                if (flag == 1)
                    this.chkXoa.Checked = true;
                else
                    this.chkXoa.Checked = false;
                reader.Dispose();
            }
            catch (Exception ex)
            {                
                MessageBox.Show(ex.Message); 
            }
        }

        private void DocNoiDungFile(string filename)
        {
                Excel.Application ExcelApp;
                Excel.Workbook objBook;
                Excel.Worksheet objSheet;
                Excel.Range range;
                object valueMissing = System.Reflection.Missing.Value;

                ExcelApp = new Excel.ApplicationClass();
                objBook = ExcelApp.Workbooks.Open(filename, valueMissing, false, valueMissing, valueMissing, valueMissing, valueMissing,
                                       Excel.XlPlatform.xlWindows, valueMissing, valueMissing,
                                       valueMissing, valueMissing, valueMissing, valueMissing, valueMissing);
                objSheet = (Excel.Worksheet)objBook.Worksheets[1];
            try
            {
                string sRange = "";
                int dong = 1;         
                


                sRange = "A" + dong.ToString();
                range = objSheet.get_Range(sRange, sRange);
                if (range.Value2 != null)
                {
                    this.txtSoPhieuPO.Text = range.Value2.ToString();
                    this.txtNgayThucHien.Text = DateTime.Today.Day.ToString() + "/" + DateTime.Today.Month.ToString() + "/" + DateTime.Today.Year.ToString();
                    this.txtNguoiThucHien.Text = _nguoitao;

                    sRange = "B" + dong.ToString();
                    range = objSheet.get_Range(sRange, sRange);
                    this.txtPlant.Text = range.Value2.ToString();

                    sRange = "C" + dong.ToString();
                    range = objSheet.get_Range(sRange, sRange);
                    this.lblLoaiPO.Text = range.Value2.ToString();

                    dong += 2;
                    sRange = "A" + dong.ToString();
                    range = objSheet.get_Range(sRange, sRange);

                    CHI_TIET_PDH oCTPDH;

                    while (range.Value2 != null)
                    {

                        oCTPDH = new CHI_TIET_PDH();
                        // ma phieu yeu cau
                        sRange = "A" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                        oCTPDH.MaPhieuYeuCau = range.Value2.ToString().Trim();
                        // ma vat tu phu tung
                        sRange = "B" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                        oCTPDH.MaThietBi = range.Value2.ToString().Trim();
                        // ten vat tu phu tung
                        sRange = "C" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                        oCTPDH.TenVTPT = range.Value2.ToString().Trim();
                        // ma trang thai
                        sRange = "D" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                        oCTPDH.MaTrangThai = int.Parse(range.Value2.ToString().Trim());
                        // so luong
                        sRange = "E" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                        oCTPDH.SoLuong = int.Parse(range.Value2.ToString().Trim());
                        // ngay giao hang
                        sRange = "F" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                        string d = (range.Value2.ToString().Trim().Substring(0, 2));
                        string m = (range.Value2.ToString().Trim().Substring(3, 2));
                        string y = (range.Value2.ToString().Trim().Substring(6, 4));
                        oCTPDH.NgayGiaoHang = Convert.ToDateTime(m + "/" + d + "/" + y);


                        // them mot dong vao danh sach 
                        oCTPDH.NgayTao = DateTime.Today;
                        oCTPDH.NguoiTao = this.txtNguoiThucHien.Text;
                        oCTPDH.POThamChieuSAP = this.txtSoPhieuPO.Text;

                        lstCTPDH.Add(oCTPDH);
                        dong++;
                        sRange = "A" + dong.ToString();
                        range = objSheet.get_Range(sRange, sRange);
                    }

                    this.gridControl1.DataSource = lstCTPDH;
                }
                else
                {

                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                objBook.Close(true, valueMissing, valueMissing);
                ExcelApp.Quit();
            }

        }

        private void cmdLuu_Click(object sender, EventArgs e)
        {
            clsPHIEU_DAT_HANG pdhCtrl = new clsPHIEU_DAT_HANG(_sConn);
            PHIEU_DAT_HANG pdh = new PHIEU_DAT_HANG();

            pdh.POThamChieuSAP = this.txtSoPhieuPO.Text.Trim();
            pdh.NgayNhap = DateTime.Today;
            pdh.NguoiNhap = this.txtNguoiThucHien.Text;
            pdh.PlanReferenceSAP = this.txtPlant.Text;
            pdh.PlantGui = this.txtPlantGui.Text;
            pdh.LoaiPO = this.txtLoaiPO.Text;

            if (chkXoa.Checked == true)
                pdh.TinhTrang = 1;
            else
                pdh.TinhTrang = 0;

            // kiem tra da ton tai du lieu Phieu_nhap_hang cho số PO này chua
            clsCHI_TIET_PNH pnhCtrl = new clsCHI_TIET_PNH(_sConn);
            List<CHI_TIET_PNH> lstPNH = new List<CHI_TIET_PNH>();
            lstPNH = pnhCtrl.usp_SelectCHI_TIET_PNH_ByPOThamChieuSAP(pdh.POThamChieuSAP);
            if (lstPNH.Count == 0)
            {
                int iResult = pdhCtrl.InsertPHIEU_DAT_HANG(pdh, lstCTPDH);
                if (iResult > 0)
                    MessageBox.Show("LƯU THÀNH CÔNG");
                else
                    MessageBox.Show("LƯU KHÔNG THÀNH CÔNG");
            }
            else
                MessageBox.Show("BẠN ĐÃ TẠO PHIẾU NHẬP HÀNG CHO PO SỐ: " + pdh.POThamChieuSAP + "\nVUI LÒNG XÓA PHIẾU NHẬP HÀNG TRƯỚC KHI CHỈNH SỬA THÔNG TIN PO!");
        }

        private void frmTaoPhieuDH_Paint(object sender, PaintEventArgs e)
        {
            //Common.PaintGradientColor(Color.LightYellow, Color.LightSkyBlue, System.Drawing.Drawing2D.LinearGradientMode.Vertical, this.Width, this.Height, this);            
        }

        private void frmTaoPhieuDH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F8)
            {
                cmdLuu_Click(null, null);
            }

        }

        private void frmTaoPhieuDH_Load(object sender, EventArgs e)
        {
            Common.SetColor(this);
        }

        

        

       
    }
}